from base64 import b64encode, b64decode
from json import dump, dumps, load
from os.path import exists
from platform import system
from subprocess import check_output
from requests import get, post
from time import strftime, localtime

url = 'http://2.2.2.3/ac_portal/login.php'

login_header = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
}

logout_header = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Refer': 'http://2.2.2.3/ac_portal/default/pc.html?type=logout',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}


def use_platform():
    print('当前操作系统 %s' % str(system()))
    return system()


def scan_wifi():
    result = check_output(['netsh', 'wlan', 'show', 'network'])
    result = result.decode('gbk')
    lst = result.split('\r\n')
    lst = lst[4:]

    for index in range(len(lst)):
        print(lst[index])
    print(result)


def get_connected_ssid():
    scan_output = check_output(['netsh', 'wlan', 'show', 'interfaces'])  # 最好使用完整路径
    x = scan_output.decode('gbk')
    current_ssid = x[2:-2].split('\r\n')[8].replace(' ', '')[5:]
    if x[2:-2].split('\r\n')[8].replace(' ', '')[:4] != 'SSID':
        arr = x[2:-2].split('\r\n')
        for i in range(len(arr)):
            if str(arr[i]).replace(' ', '')[:4] == 'SSID':
                current_ssid = str(arr[i]).replace(' ', '')[5:]
                return current_ssid
        if str(arr[7]).replace(' ', '')[:2] == '状态':
            current_ssid = str(arr[7]).replace(' ', '')[3:]
        else:
            for i in range(len(arr)):
                if str(arr[i]).replace(' ', '')[:2] == '状态':
                    current_ssid = str(arr[i]).replace(' ', '')[3:]
                    break
    return current_ssid


def login(ssid, username, password):
    if ssid != 'UESTC':
        print('UESTC校园网未连接，原因：%s' % str(ssid).replace(":", ''))
        return None

    print('开始登录UESTC校园网。。。')
    post_url = url
    post_data = {
        'opr': 'pwdLogin',
        'userName': username,
        'pwd': password,
        'rememberPwd': 1
    }
    response = post(post_url, data=post_data, headers=login_header)
    # print(f"状态码：{response.status_code}")
    # print(f"返回内容：{response.text}")
    if response.status_code == 200 and response.text.__contains__("'msg':'logon success'"):
        print('登录成功！', strftime("%Y-%m-%d %H:%M:%S", localtime()))
        return True
    return False


def logout(ssid):
    if ssid != 'UESTC':
        print('未连接校园网 UESTC ，原因 >>> ' + ssid)
        return None
    post_url = url
    post_data = {
        'opr': 'logout'
    }
    response = post(post_url, data=post_data, headers=logout_header)
    # print(f"状态码：{response.status_code}")
    # print(f"返回内容：{response.text}")
    if response.status_code == 200:
        if response.text.__contains__("'success':true"):
            print('开始退出UESTC校园网...')
            print('成功退出登录！', strftime("%Y-%m-%d %H:%M:%S", localtime()))
            return True
        else:
            return False


def check_connection(test_url='https://www.baidu.com'):
    r = get(url=test_url, headers=login_header, timeout=5)
    if r.status_code != 200:
        print('测试 >>> 无法连接互联网：status code=%s' % str(r.status_code))
        return False
    else:
        print('测试 >>> 已连接互联网')
        return True


def user_info_storage(username, password):
    password = b64encode(str(password).encode()).decode()
    userinfo = dumps({'username': username, 'password': password}, sort_keys=True, indent=4, ensure_ascii=False)
    with open(file='user_info.json', mode='w', encoding='utf8') as json_file:
        dump(userinfo, json_file, ensure_ascii=False)
        print('用户信息json已存储！')


def get_user_info():
    result = []
    with open(file='user_info.json', mode='r', encoding='utf8') as json_file:
        data = load(json_file)
        password = b64decode(eval(data)['password']).decode()
        result.append(eval(data)['username'])
        result.append(password)

    return result


def main():
    print('***********UESTC校园网自动登录/登出程序***********')
    if use_platform() == 'Windows':
        ssid = get_connected_ssid()
        if ssid != 'UESTC':
            print('未连接校园网 UESTC ，原因 >>> ' + ssid)
        else:
            username, password = ['', '']
            if exists('user_info.json'):
                print('>>> 已读取用户存储信息')
                username, password = get_user_info()
            else:
                username = input('用户名：')
                password = input('密码：')
                confirm_password = input('确认密码：')
                while password != confirm_password:
                    password = input('密码：')
                    confirm_password = input('确认密码：')
                # user_info_storage(username, password)

            # ssid = get_connected_ssid()
            res = logout(ssid)
            if res is not None and not res:
                login_res = login(ssid, username, password)
                if login_res is True and not exists('user_info.json'):
                    # 登录成功则存储用户信息
                    user_info_storage(username, password)
    else:
        username, password = ['', '']
        if exists('user_info.json'):
            print('>>> 已读取用户存储信息')
            username, password = get_user_info()
        else:
            username = input('用户名：')
            password = input('密码：')
            confirm_password = input('确认密码：')
            while password != confirm_password:
                password = input('密码：')
                confirm_password = input('确认密码：')
            res = logout('UESTC')
            if res is not None and not res:
                login_res = login('UESTC', username, password)
                if login_res is True and not exists('user_info.json'):
                    # 登录成功则存储用户信息
                    user_info_storage(username, password)


if __name__ == '__main__':
    try:
        main()
    except ModuleNotFoundError as e:
        print(e)
    except Exception as e:
        print(e)
    finally:
        input('>>> 按任意键退出')
